<template>
    <div class="admin">
        <div class="left"><el-input clearable placeholder="请输入部门名称" prefix-icon="el-icon-search" v-model="filterText">
            </el-input>
            <el-tree :data="data" default-expand-all :props="defaultProps" :filter-node-method="filterNode" ref="tree" @node-click="handleCheckChange"></el-tree>
        </div>
        <div class="right">
            <div class="search" v-show="searchShow">
                <div class="search_input">
                    <span>用户名称</span>
                    <el-input placeholder="输入用户名称" clearable v-model="keyword.userName"></el-input>
                </div>
                <div class="search_input">
                    <span>手机号码</span>
                    <el-input placeholder="请输入手机号码" clearable v-model="keyword.phonenumber"></el-input>
                </div>
                <div class="search_input">
                    <span>状态</span>
                    <el-select placeholder="用户状态" clearable v-model="keyword.status">
                        <el-option value="0" label="正常"></el-option>
                        <el-option value="1" label="停用"></el-option>
                    </el-select>
                </div>


            </div>
            <div class="bootom">
                <div class="search_input">
                    <span>创建时间</span>
                    <el-date-picker clearable type="daterange" v-model="time" range-separator="-" start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="yyyy-MM-dd">
                    </el-date-picker>
                </div>
                <div class="elbtn">
                    <el-button type="primary" size="mini" icon="el-icon-search" @click="searchFn">搜索</el-button>
                    <el-button size="mini" icon="el-icon-refresh" @click="ResetFn">重置</el-button>
                </div>

            </div>
            <div class="nav">
                 <div class="btn">
                <el-button type="primary" plain size="mini" icon="el-icon-plus" @click="addFn">新增</el-button> <el-button
                    type="success" plain size="mini" icon="el-icon-edit" :disabled="editDisabled" @click="editUser(editId)">修改</el-button> <el-button
                    type="danger" plain size="mini" icon="el-icon-delete" :disabled="delDisabled" @click="delUsersFn(delId)">删除</el-button> <el-button type="info"
                    plain size="mini" icon="el-icon-upload2" @click="importDataFn">导入</el-button> <el-button type="warning" plain size="mini"
                    icon="el-icon-download" @click="exportFn">导出</el-button>
                    <el-dialog
  title="用户导入"
  :visible.sync="importDataShow"
  width="30%"
  >
  <el-upload
  class="upload-demo"
  drag
  accept=".xls,.xlsx"
  action="https://jsonplaceholder.typicode.com/posts/"
  multiple>
  <i class="el-icon-upload"></i>
  <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
  <div class="el-upload__tip" slot="tip"> <el-checkbox v-model="checked"></el-checkbox>是否更新已经存在的用户数据</div>
  <div class="el-upload__tip" slot="tip">仅允许导入xls、xlsx格式文件。</div>
</el-upload>
  <span slot="footer" class="dialog-footer">
    <el-button @click="importDataShow = false">取 消</el-button>
    <el-button type="primary" @click="importFn">确 定</el-button>
  </span>
</el-dialog>
            </div>
            <div class="Development">
                <el-tooltip class="item" effect="dark" content="隐藏搜索" placement="top">
       <el-button @click="searchShowFn" icon="el-icon-search" circle size="mini"></el-button>
    </el-tooltip>
    <el-tooltip class="item" effect="dark" content="刷新" placement="top">
        <el-button @click="getUserList(pageNum1, pageSize1)" icon="el-icon-refresh" circle size="mini"></el-button>
    </el-tooltip> 
     <el-tooltip class="item" effect="dark" content="显影列" placement="top">
        <el-button @click="developmentShowFn" icon="el-icon-menu" circle size="mini"></el-button>
    </el-tooltip>
    <el-dialog
  title="显示/隐藏"
  :visible.sync="developmentShow">
  <el-transfer
    v-model="value"
    :titles="['显示', '隐藏']"
    @change="handleChange"
    :data="developmentData">
  </el-transfer>
</el-dialog>
              
            </div>
            </div>
           
            <el-table  @selection-change="handleSelectionChange" :data="tableData" style="width: 100%">
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column v-if="HideArr[0]" prop="userId" label="用户编号" align="center" width="98">
                </el-table-column>
                <el-table-column v-if="HideArr[1]" prop="userName" label="用户名称" align="center">
                </el-table-column>
                <el-table-column v-if="HideArr[2]" prop="nickName" label="用户昵称" align="center">
                </el-table-column> <el-table-column v-if="HideArr[3]" prop="dept.deptName" label="部门" align="center">
                    <template #default="{ row }">
                        <span v-if="row.dept">{{ row.dept.deptName }}</span>
                        <span v-else>若依科技</span>
                    </template>
                </el-table-column> <el-table-column v-if="HideArr[4]" prop="phonenumber" label="手机号码" align="center" width="120">
                </el-table-column>
                <el-table-column v-if="HideArr[5]" prop="status" label="状态" align="center">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" active-value="0" inactive-value="1"
                            @change="switchStatus(row)" />
                    </template>
                </el-table-column> <el-table-column v-if="HideArr[6]" prop="createTime" label="创建时间" align="center" width="160">
                    <template #default="{ row }">
                        {{ row.createTime | dateFormat }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="200">
                    <template  #default="{ row }">
                   <div v-if="row.userId==1"></div>
                   <div v-else><el-button type="text" size="mini" icon="el-icon-edit"
                            @click="editUser(row.userId)">修改</el-button>
                        <el-button type="text" size="mini" icon="el-icon-delete" @click="delUserFn(row)">删除</el-button>
                        <el-dropdown>
                            <el-button type="text" size="mini" icon="el-icon-d-arrow-right">更多</el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item><i class="el-icon-key"></i><span
                                        @click="resetPwdShowFn(row)">重置密码</span></el-dropdown-item>
                                <el-dropdown-item><i class="el-icon-circle-check"></i> <span @click="$router.push(`user-auth/role?id=${row.userId}`)">分配角色</span></el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                        <el-dialog title="提示" :visible.sync="resetPwdShow" width="30%" @close="resetPwdShow = false">
                            <span>请输入"{{ resetUserName }}"的新密码</span>
                            <el-input v-model="resetPwdPassword"></el-input>
                            <span slot="footer" class="dialog-footer">
                                <el-button @click="resetPwdShow = false">取 消</el-button>
                                <el-button type="primary" @click="resetPwdFn(row)">确 定</el-button>
                            </span>
                        </el-dialog></div>
                    </template>
                </el-table-column>
            </el-table>

            <div class="page">
                <el-pagination :page-size="pageSize" :page-sizes="[10, 20, 30, 50]" background
                    :current-page="currentPage" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
            <addUser :show="isShow" :data="data"  @fn="closeFn" :id="editId" />

        </div>
    </div>
</template>

<script>
import { treeselectAPI, userListApi, changeStatusAPI, deleteUserAPI, resetPwdAPI ,deleteUsersAPI,importDataAPI,exportAPI,searchUserListApi} from "@/API/hbaip/api";
import addUser from "./addUser.vue"
import {saveAs} from "file-saver"
export default {
    data() {
        const cities = ['用户编号', '用户名称', '用户昵称', '部门', '手机号码', '状态', '创建时间'];
        const generateData = () => {
        const developmentData = [];
        for(let i =0;i<cities.length;i++){
            developmentData.push({
                key:cities[i],
                label:cities[i]
            })
        }
        return developmentData;
      };
      const TableColsData = (generateData())
      const HideArr =[true, true, true, true, true, true, true];
      const handleChange=(val)=>{
            if(val.length===0){
                HideArr=[true, true, true, true, true, true, true];
            }
            for(let i = 0;i<cities.length;i++){
                for(let j =0;j<val.length;j++){
                    if(cities[i]===val[j]){
                        HideArr[i]=false;
                        break;
                    }
                    if(j==val.length-1){
                        HideArr[i]=true;
                    }
                }
            }
        }
        return {
            data: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            developmentData:TableColsData,
            value:[],
            handleChange:handleChange,
            HideArr:HideArr,
            tableData: [],
            filterText: '',
            time:[],
            total: 0,
            pageNum: 1,
            pageSize:
                10,
            deptId:
                0,
            currentPage: 1,
            keyword: {
                pageNum: 1,
                pageSize:10,
                userName: undefined,
                phonenumber: undefined,
                status: undefined,
                'params[beginTime]':'',
                'params[endTime]':'',
            },
            searchShow:true,
            developmentShow:false,
            isShow: false,
            editId: 0,
            resetPwdShow: false,
            resetUserName: '',
            resetPwdPassword:'',
            editDisabled:true,
            delDisabled:true,
            valLength:0,
            delId:[],
            pageNum1:1,
            pageSize1:10,
            importDataShow:false,
            checked:false,
        };
    },
    // 监听左边搜索
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      }
    },
    components: { addUser },
    async created() {
        let res = await treeselectAPI()
        this.data = res.data
        this.getUserList(this.pageNum, this.pageSize);
    },
    methods: {
       
        // 显影列
        developmentShowFn(){
            this.developmentShow=!this.developmentShow
        },
        // 隐藏搜索
        searchShowFn(){
this.searchShow=!this.searchShow
        },
        //导出
        async exportFn(){
            let res = await exportAPI(
        {
          pageNum: this.pageNum1,
          pageSize: this.pageSize1,
        },
        {
          //导出文件的请求需要额外配置
          headers: { "Content-Type": "application/x-www-form-urlencoded" },
          responseType: "blob",
        }
      );
      if (!res) return;
      saveAs(
        new Blob([res]),
        `用户管理_${new Date().getTime()}.xlsx`
      );
        },
        // 导入显示
        importDataFn(){
            this.importDataShow=true
        },
        // 导入
        async importFn(){
let res = await importDataAPI({
    updateSupport:this.checked
    
})
this.importDataShow=false
        },
        // 修改是否禁用修改和删除按钮
        handleSelectionChange(val){
            val.map((item)=>{
               this.editId=item.userId
            })
            this.delId = val.map((item)=>item.userId)
          
            this.valLength=val.length
           if(val.length>=1 &&val.length<2){
            this.editDisabled=false
            this.delDisabled=false
           }else{
            this.editDisabled=true
            this.delDisabled=false
           }
        },
        // 左边搜索
        filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
    //   点击左边树状数据筛选表格数据
      async handleCheckChange(data){
        let res = await userListApi({
                pageNum:this.pageNum1,
                pageSize:this.pageSize1,
                deptId:data.id
            })
            this.tableData = res.rows
            this.total = res.total
      },
        handleSizeChange(val) {
            let res = userListApi({
                pageNum: 1,
                pageSize: val,
            }).then((d) => {
                this.tableData = d.rows;
                this.total = d.total;
            });
            this.pageSize1=val
        },
        handleCurrentChange(val) {
            let res = userListApi({
                pageNum: val,
                pageSize: 10,
            }).then((d) => {
                this.tableData = d.rows;
                this.total = d.total;
            });
            this.pageNum1 = val;
        },
        // 封装表格请求数据
        async getUserList(pageNum, pageSize) {
            let res = await userListApi({
                pageNum,
                pageSize,
            })
            this.tableData = res.rows
            this.total = res.total
        },
        // 右边搜索
         searchFn() {
            this.keyword["params[beginTime]"] = this.time[0]
            this.keyword["params[endTime]"] = this.time[1]
            searchUserListApi(this.keyword).then((res)=>{
                  this.tableData = res.rows
            this.total = res.total
            })
        },
        // 重置
        ResetFn() {
            this.keyword.userName = '';
            this.keyword.phonenumber = '';
            this.keyword.status = '';
            this.time=[];
            this.getUserList(this.pageNum, this.pageSize);
        },

        closeFn(val) {
            if (val) this.getUserList(this.pageNum1, this.pageSize1)
            this.isShow = false
            this.editId=0
        },
        getTreeList(){
            this.getUserList(this.pageNum,this.pageSize)
        },
        // 添加
        addFn() {
            this.isShow = true
        },
        // 修改
        editUser(id) {
            this.editId = id;
            this.isShow = true
        },
        // 批量删除
        delUsersFn(id){
            if(this.valLength>=1 &&this.valLength<2){
                this.$confirm(`是否确认删除用户编号为"${id}"的数据项？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await deleteUserAPI(id)
                if (res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getUserList(this.pageNum1, this.pageSize1)
                } else {
                    this.$message({
                        type: 'error',
                        message: '删除失败!'
                    });
                }

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
            }else{
                this.$confirm(`是否确认删除用户编号为"${id}"的数据项？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await deleteUsersAPI(id)
                if (res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getUserList(this.pageNum1, this.pageSize1)
                } else {
                    this.$message({
                        type: 'error',
                        message: '删除失败!'
                    });
                }

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
            }
        },
        //  删除
        delUserFn(row) {
            this.$confirm(`是否确认删除用户编号为"${row.userId}"的数据项？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await deleteUserAPI(row.userId)
                if (res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getUserList(this.pageNum1, this.pageSize1)
                } else {
                    this.$message({
                        type: 'error',
                        message: '删除失败!'
                    });
                }

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        // 修改状态
        switchStatus(row) {
            this.$confirm(`确认要"${row.status == 0 ? '启用' : '停用'}"${row.userName}"用户吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await changeStatusAPI({
                    status: row.status, userId: row.userId
                }
                )
                if (res.code == 200) {
                    this.$message({
                        type: 'success',
                        message: '修改成功!'
                    });
                } else {
                    row.status = row.status === 0 ? 1 : 0;
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
                row.status = row.status === 0 ? 1 : 0;
            });
        },
        resetPwdShowFn(row) {
            this.resetPwdShow = true
            this.resetUserName = row.userName
        },
         resetPwdFn(row) {
            this.$confirm('确定要修改密码', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let res = await resetPwdAPI({
                password:this.resetPwdPassword,
                userId: row.userId
            })
                if (res.code === 200) {
                    this.$message({
                        type: 'success',
                        message: '修改密码成功!'
                    });
                    this.resetPwdShow=false
                    this.getUserList(this.pageNum1, this.pageSize1)
                } else {
                    this.$message({
                        type: 'error',
                        message: '修改密码失败!'
                    });
                }

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
           
            
        }
    }
}
</script>

<style scoped lang="less">
.admin {
    display: flex;
    justify-content: space-between;
    .left{
        width: 16.6666666667%;
    }
    .right {
        width: 83.3333333333%;

        .search {
            padding: 20px 0;
            display: grid;
            grid-template-columns: repeat(3, 33%);

            .search_input {
                display: flex;
                margin-right: 20px;
                align-items: center;
                width: 300px;
                margin-left: 40px;
                margin-bottom: 20px;

                span {
                    width: 125px;
                    // margin-right: 5px;
                    font-weight: 700;
                    font-size: 14px;
                    color: #606266;
                }
            }
        }

        .bootom {
            display: flex;

            .search_input {
                display: flex;
                margin-right: 20px;
                align-items: center;
                width: 300px;
                margin-left: 40px;
                margin-bottom: 20px;

                span {
                    width: 125px;
                    // margin-right: 12px;
                    font-weight: 700;
                    font-size: 14px;
                    color: #606266;
                }
            }

            .elbtn {
                margin-top: 6px;
            }
        }
        .nav{
            margin-left: 40px;
            margin-bottom: 8px;
            display: flex;
            justify-content: space-between;
        }

.upload-demo{
    text-align: center;
}
        /deep/ .el-table .el-table__header-wrapper th {
            background-color: #f8f8f9;
            color: #515a6e;
            height: 40px;
            font-size: 13px;
            font-weight: 700;
        }

        /deep/ .el-dropdown-link {
            cursor: pointer;
            color: #409EFF;
        }

        /deep/ .el-dropdown {
            margin-left: 10px;
        }

        .page {
            padding: 20px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>